from datetime import date, timedelta
from chapterlib import get_chapter_info, fmt_to_str


def adjust_args(local_data):

    local_stored_date = date.fromisoformat(local_data.get('date'))
    this_week = get_a_week()
    before_this_week = (this_week[-1]-local_stored_date).days >= 0
    if before_this_week:
        monday = this_week[0]
    else:
        monday = get_a_week(False)[0]

    delta = (monday - local_stored_date).days

    if delta:
        # if delta基本为true, 因为本地存储的是一周的最后一天(详见当前模块的get_data函数)
        juan1 = local_data.get('juan1')
        zhang1 = int(local_data.get('zhang1'))
        capacity1 = int(local_data.get("capacity1"))
        juan2 = local_data.get('juan2')
        zhang2 = int(local_data.get('zhang2'))
        capacity2 = int(local_data.get("capacity2"))

        reset_chapter1 = get_chapter_info(juan1, zhang1, capacity1, skip=delta)
        reset_chapter2 = get_chapter_info(juan2, zhang2, capacity2, skip=delta)
        return *reset_chapter1, capacity1, *reset_chapter2, capacity2, monday.isoformat()


def get_weekly_data(data: dict):
    skip = -7 if int(data.get('isthisweek')) else 7
    reset_chapter1 = get_chapter_info(data.get('juan1'), int(
        data.get('zhang1')), int(data.get('capacity1')), skip=skip)
    reset_chapter2 = get_chapter_info(data.get('juan2'), int(
        data.get('zhang2')), int(data.get('capacity2')), skip=skip)
    data.update({'juan1': reset_chapter1[0], 'zhang1': reset_chapter1[1],
                'juan2': reset_chapter2[0], 'zhang2': reset_chapter2[1]})
    return data


def get_data(data: dict):

    juan1 = data.get('juan1')
    zhang1 = int(data.get('zhang1'))
    capacity1 = int(data.get("capacity1"))
    juan2 = data.get('juan2')
    zhang2 = int(data.get('zhang2'))
    capacity2 = int(data.get("capacity2"))

    dujing_1 = get_chapter_info(juan1, zhang1, capacity1)
    dujing_2 = get_chapter_info(juan2, zhang2, capacity2)

    date_list = get_a_week(int(data.get('isthisweek')))
    daogao_dict = parse_text(data.get('msg'))

    web_data = []

    for i, key in enumerate(sorted(daogao_dict.keys())):
        dujing_i_1 = dujing_1[i]
        dujing_i_2 = dujing_2[i]
        if text_info := daogao_dict.get(key):
            aday = date_list[key-1]
            day_text = get_date_info(aday)
            web_data.append([day_text, fmt_to_str(dujing_i_1),
                            fmt_to_str(dujing_i_2), text_info])

    ks = ('date', 'juan1', 'zhang1', 'capacity1',
          'juan2', 'zhang2', 'capacity2')
    vs = (aday.isoformat(), dujing_i_1[0][0], dujing_i_1[0][2][0],
          capacity1, dujing_i_2[0][0], dujing_i_2[0][2][0], capacity2)
    return web_data, dict(zip(ks, vs))


def parse_text(text):

    text_raw = text.strip()
    d = dict()
    # 有效字数在3~800之间, 如果不在范围, 抛出空数据
    if not 4 < len(text_raw) < 800:
        return d

    options = ('周一', '周二', '周三', '周四', '周五', '周六', '周日')

    key = 0
    values = []
    for line in text_raw.splitlines():
        line = line.strip()
        if line:
            if line in options:
                # 读取到新key就储存上次的k:v
                # if key的作用是排除首次读取到的key,那时上次的k:v为空值
                # 也可以用if values,但因为程序逻辑变更,须存储所有用户输入的key,即使value为空
                # 每日最多5个祷告事项, 一个祷告事项最多40个字(原本需在前端实现, 以后再说)
                if key:
                    d[key] = values[:4]
                    values = []
                key = week_info_to_int(line)
            else:
                if len(line) > 40:
                    line = line[:40] + '...'
                values.append(line)
    # 除了排除首次空k:v,还要追加最后一次k:v
    if key:
        d[key] = values[:4]
        values = []

    return d


def week_info_to_int(week):
    week_dict = {'周一': 1, '周二': 2, '周三': 3,
                 '周四': 4, '周五': 5, '周六': 6, '周日': 7}
    return week_dict.get(week)


def get_week_info(aday):
    week_dict = {1: '周一', 2: '周二', 3: '周三',
                 4: '周四', 5: '周五', 6: '周六', 7: '周日'}
    return week_dict.get(aday.isoweekday())


def get_date_info(mydate):
    return f'{mydate.month:02}月{mydate.day:02}日 · {get_week_info(mydate)}'


def get_a_week(isthisweek=True):
    oneday = timedelta(days=1)
    week_list = []
    today = date.today()

    if isthisweek:
        days = today.isoweekday()-1
        td = timedelta(days=days)
        init_day = today - td
    else:
        days = 7-today.isoweekday()+1
        td = timedelta(days=days)
        init_day = today + td

    for i in range(7):
        week_list.append(init_day)
        init_day += oneday

    return week_list


if __name__ == '__main__':
    print(get_a_week())
    print(get_a_week(False))
